import { addUserRoleAPI, pageRole } from '@/pages/system/role/api';
import { API } from '@/services/typings';
import { AppstoreAddOutlined } from '@ant-design/icons';
import { ActionType, ModalForm, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-table';
import { Button, message, Popconfirm, Tooltip } from 'antd';
import React from 'react';

interface RoleAssignmentModalProps {
  userId: string;
}

const AddRoleMoadl: React.FC<RoleAssignmentModalProps> = ({ userId }) => {
  const actionRef = React.useRef<ActionType>();
  const columns: ProColumns<API.IRole>[] = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '角色键值',
      dataIndex: 'roleKey',
      key: 'roleKey',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <Popconfirm
          title={'确认添加用户角色吗？'}
          key="delete"
          onConfirm={async () => {
            const { data } = await addUserRoleAPI(record.id as any, userId);
            if (data) {
              actionRef.current?.reload();
              message.success('删除成功');
            }
          }}
        >
          <a>添加</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <ModalForm
      title={'分配角色'}
      autoFocusFirstInput
      trigger={
        <Tooltip title="新增角色">
          <Button shape="circle" size="small" icon={<AppstoreAddOutlined />} />
        </Tooltip>
      }
      modalProps={{ destroyOnClose: true }}
    >
      <ProTable<API.IRole>
        rowKey="id"
        headerTitle={'已存在角色列表'}
        columns={columns as any}
        request={async (params) => {
          const { data } = await pageRole({ ...params, userId: userId, includeUser: 'not' });
          return data;
        }}
        actionRef={actionRef}
        tableAlertRender={false}
        size={'small'}
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 10,
        }}
      />
    </ModalForm>
  );
};

export default AddRoleMoadl;
